const app = getApp()
// var ports = require('../../../utils/ports'); // 接口地址
// var toast = require('../../../utils/toast/toast.js'); //统一提示弹窗
// var config = require('../../../utils/apis/config.js'); // 接口地址apiHttp
// var utils = require('../../../utils/util.js'); // 接口地址apiHttp
import inBleOpen from './js/InBleOpen.js'
import peakeBleOpen from './js/PeakeBleOpen.js'
import bosinyBleOpen from './js/BosinyBleOpen.js'
import bluetoothSortingScan from './js/BluetoothSortingScan.js'
Page({
  data: {
    showSheet: false,
    isFirst: true,
    actions: [],
    statusBarHeight: app.globalData.statusBarHeight,
    isShare: false,
    deviceList: [],
    havePermission: false,
    currentStatus: {},
    status: {
      searching: {
        type: 'searching',
        tip: '正在连接',
        subtip: '正在搜索蓝牙设备',
        icon: '/property/image/openDoor/open_2.png'
      },
      opening: {
        type: 'open',
        tip: '正在开门',
        subtip: '正在打开蓝牙设备',
        icon: '/property/image/openDoor/open.png'
      },
      open: {
        type: 'open',
        tip: '一键开门',
        subtip: '请长按上方按钮选择开锁',
        icon: '/property/image/openDoor/open.png'
      },
      success: {
        type: 'success',
        tip: '开门成功',
        subtip: '欢迎光临',
        icon: '/property/image/openDoor/unlocked.png'
      },
      fail: {
        type: 'fail',
        tip: '开门失败',
        subtip: '请联系物业人员',
        icon: '/property/image/openDoor/locked.png'
      },
      cannotConnect: {
        type: 'cannotConnect',
        tip: '连接失败',
        subtip: '请联系物业人员',
        icon: '/property/image/openDoor/disConnect.png'
      },
      noDivice: {
        type: 'cannotConnect',
        tip: '连接失败',
        subtip: '未找到设备',
        icon: '/property/image/openDoor/disConnect.png'
      },
    }
  },

  async onLoad(options) {
    this.setData({
      currentStatus: this.data.status.searching
    })
    /*if (options.isShare && options.isShare == 'true') {
      this.setData({
        isShare: true
      })
    }*/
  },


  async onShow() {
    this.getLocation()
    /*const ret = await app.userLogin()
    if (ret) {
      this.getLocation()
    }*/
  },

  // 调用地理位置授权
  getLocation() {
    const that = this;
    wx.getLocation({
      type: "gcj02",
      isHighAccuracy: true,
      success(res) {
        that.startBlue();
      },
      fail(err) {
        that.setData({
          currentStatus: that.data.status.cannotConnect
        })
        wx.getSetting({
          success(res) {
            if (!res.authSetting["scope.userLocation"]) {
              wx.showModal({
                content: '授权失败，请重新授权位置信息',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      withSubscriptions: false,
                    })
                  }
                }
              })
            } else {
              wx.showModal({
                content: '授权失败，请在系统设置中打开定位服务'
              })
            }
          }
        })
      }
    });
  },

  //启动蓝牙检测
  startBlue() {
    const that = this
    wx.openBluetoothAdapter({
      success() {
        that.getAdapterState()
      },
      fail: function (res) {
        wx.showModal({
          content: '请开启手机蓝牙后再试'
        })

        that.setData({
          currentStatus: that.data.status.cannotConnect
        })
        wx.onBluetoothAdapterStateChange(function (res) { //监听蓝牙打开关闭
          if (res.available) {
            that.setData({
              currentStatus: that.data.status.searching
            })
            console.log("用户已手动开启蓝牙，检查是否可用")
            that.getAdapterState();
          }
        })
      }
    })
  },
  getAdapterState() {
    const that = this
    wx.getBluetoothAdapterState({
      success: function (res) {
        console.log('蓝牙状态', res);
        //discovering 是否正在搜索设备  available 蓝牙适配器是否可用
        if (res.available == false) {
          that.setData({
            currentStatus: that.data.status.cannotConnect
          })
          toast.showToast("当前蓝牙不可用");
        } else if (res.discovering == false) {
          that.scanBluetoothDevice();
        } else if (res.available) {
          that.scanBluetoothDevice();
        }
      },
      fail() {
        toast.showToast("当前蓝牙不可用,请断开其他连接重试");
        that.setData({
          currentStatus: that.data.status.cannotConnect
        })
      }
    })
  },

  //蓝牙扫描门禁设备
  scanBluetoothDevice() {
    const that = this
    bluetoothSortingScan.start("", async (res) => {
      console.log(res);
      if (res.length > 0) {
        //有权限开门的机器列表 鉴别权限
        const authList = await that.checkPermission(res)
        that.setData({
          deviceList: authList
        })
        if (authList.length <= 0) {
          //列表没有值
          that.setData({
            currentStatus: that.data.status.noDivice
          })
        } else {
          //列表有值
          that.setData({
            currentStatus: that.data.status.open
          })
          if (this.data.isFirst) {
            that.unlockDoorHandle()
            that.setData({
              isFirst: false
            })
          }
        }
      } else {
        //未找到门禁设备
        that.setData({
          currentStatus: that.data.status.noDivice
        })
      }
    })
  },

  async unlockDoorHandle() {
    if (this.data.currentStatus == this.data.status.success) {
      return
    }

    if (this.data.deviceList.length === 1) {
      //只有一台门禁设备
      let tmp = this.data.deviceList[0]
      tmp.deviceName = tmp.name
      this.openDoor(tmp)
    } else if (this.data.deviceList.length > 1) {
      //不止一台门禁设备
      console.log(this.data.deviceList);
      //弹选择框
      this.setData({
        showSheet: true,
        actions: this.data.deviceList.map(item => {
          return {
            ...item,
            deviceName: item.name,
            name: item.lockName
          }
        }).slice(0, 5)
      })
    } else {
      console.log('没有权限');
    }
  },

  async checkPermission(deviceList) {
    let data = {
      locks: deviceList
    }
    const ret = await app.agriknow.sgin_request(ports.doorPermission, data)
    if (ret.code === 200) {
      console.log(ret.data);
      return ret.data
    } else {
      toast.showToast(ret.message);
    }
  },

  //返回首页
  backHandle: function () {
    if (this.data.isShare) {
      wx.switchTab({
        url: '/pages/home/home',
      })
    } else {
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  //查看门锁记录
  unlockRecordHandle() {
    wx.navigateTo({
      url: '/property/pages/unlockRecord/unlockRecord',
    })
  },

  //开门操作
  openDoor({
    id,
    deviceId,
    deviceName,
    encryFlag
  }) {
    this.setData({
      currentStatus: this.data.status.opening
    })
    const that = this
    if (deviceName.startsWith('06')) {
      // 博西尼设备开门
      bosinyBleOpen.ConnectTo(deviceId, deviceName, 0, function (res) {
        switch (res.state) {
          case 'OK':
            wx.vibrateLong({
              success: (res) => {},
            })
            that.addOpenLockBill(id, 1, '开门 成功')
            break;
          case '002':
            that.addOpenLockBill(id, 0, '未扫描到门禁设备，请确认周围环境已安装门禁设备或者您可以尝试重启蓝牙后在开门')
            break;
          case '003':
            that.addOpenLockBill(id, 0, '发送开门信息失败')
            break;
          case '004':
            that.addOpenLockBill(id, 0, '蓝牙连接失败，请尝试重启蓝牙后在开门')
            break;
          default:
            that.addOpenLockBill(id, 0, '请尝试重启蓝牙后在开门')
            break;
        }
      })
    } else if (deviceName.startsWith('C3') || deviceName.startsWith('C6')) {
      peakeBleOpen.ConnectTo(deviceName, deviceId, function (res) {
        switch (res.state) {
          case 'OK':
            wx.vibrateLong({
              success: (res) => {},
            })
            that.addOpenLockBill(id, 1, '开门 成功')
            break;
          case '002':
            that.addOpenLockBill(id, 0, '未扫描到门禁设备，请确认周围环境已安装门禁设备或者您可以尝试重启蓝牙后在开门')
            break;
          case '003':
            that.addOpenLockBill(id, 0, '连接门禁设备失败，请尝试重启蓝牙后在开门')
            break;
          case '004':
            that.addOpenLockBill(id, 0, '蓝牙连接失败，请尝试重启蓝牙后在开门')
            break;
          default:
            that.addOpenLockBill(id, 0, '请尝试重启蓝牙后在开门')
            break;
        }
      })
    } else {
      inBleOpen.ConnectTo(deviceName, encryFlag, deviceId, function (res) {
        switch (res.state) {
          case 'OK':
            wx.vibrateLong({
              success: (res) => {},
            })
            that.addOpenLockBill(id, 1, '开门 成功')
            break;
          case '002':
            that.addOpenLockBill(id, 0, '未扫描到门禁设备，请确认周围环境已安装门禁设备或者您可以尝试重启蓝牙后在开门')
            break;
          case '003':
            that.addOpenLockBill(id, 0, '连接门禁设备失败，请尝试重启蓝牙后在开门')
            break;
          case '004':
            that.addOpenLockBill(id, 0, '蓝牙连接失败，请尝试重启蓝牙后在开门')
            break;
          default:
            that.addOpenLockBill(id, 0, '请尝试重启蓝牙后在开门')
            break;
        }
      })
    }
  },

  //记录开门日志
  async addOpenLockBill(id, flag, desc) {
    const that = this
    if (flag === 1) {
      that.setData({
        currentStatus: that.data.status.success
      })
    } else {
      this.setData({
        currentStatus: this.data.status.fail
      })
    }
    setTimeout(() => {
      that.setData({
        currentStatus: that.data.status.open
      })
    }, 5000);
    console.log('记录日志');
    let data = {
      id,
      flag,
      desc
    }

    const ret = await app.agriknow.sgin_request(ports.addOpenLockBill, data)
    if (ret.code === 200) {} else {
      toast.showToast(ret.message);
    }
  },
  //关闭选择要开启的门禁
  onSheetClose() {
    this.setData({
      showSheet: false
    });
  },
  //选择好了要开启的门禁
  onSheetSelect(event) {
    console.log(event.detail);
    let selectInfo = event.detail
    this.openDoor(selectInfo)
  },
})